/**
 * 
 */
package hu.gbalage.owlforms.xforms;

import hu.gbalage.owlforms.api.Form;
import hu.gbalage.owlforms.api.data.FormData;
import hu.gbalage.owlforms.xforms.work.Boot;
import hu.gbalage.owlforms.xforms.work.FormsCache;
import hu.gbalage.owlforms.xforms.work.IOWLForms;
import hu.gbalage.owlforms.xforms.xhtml.XHTMLBase;

import java.io.IOException;
import java.io.PrintStream;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * @author Grill Balazs (balage.g@gmail.com)
 *
 */
public class TestHandler implements HttpHandler {

	/* (non-Javadoc)
	 * @see com.sun.net.httpserver.HttpHandler#handle(com.sun.net.httpserver.HttpExchange)
	 */
	@Override
	public void handle(HttpExchange arg0) throws IOException {
		
		try{
			
			String uri = arg0.getRequestURI().getQuery();
			
			if (uri.startsWith("uri=")) uri = uri.substring(4);
			
			Form form = FormsCache.getForm(IOWLForms.Form_Szoctam);
			
			FormData loaded = Boot.load(form, uri);
			
			arg0.getResponseHeaders().add("Content-Type", "application/xhtml+xml");
			
			arg0.sendResponseHeaders(200, 0);
		
			XHTMLBase base = new XHTMLBase("Result");
			
			FormDataPrinter printer = new FormDataPrinter();
			
			base.body.appendChild(printer.toXHTML(base.doc, loaded));
			
			XMLHelper.serialize(base.doc, arg0.getResponseBody());
	
		}catch(Exception e){
			//System.err.println(e);
			e.printStackTrace();
			arg0.sendResponseHeaders(500, 0);
			PrintStream p = new PrintStream(arg0.getResponseBody());
			e.printStackTrace(p);
		}
		
		arg0.close();
	}

}
